<script setup lang="ts">
import { onMounted, nextTick, computed, watch } from 'vue';
import { useWebSocket } from '../stores/websocket'
import liveList from '../components/liveList.vue'
import { useCounterStore } from '../stores/counter'
import { wsUrl } from '../utils/config'
const {
  status,
  reconnectCount,
  receivedMessages,
  init,
  connect,
  disconnect,
  send,
  clearMessages
} = useWebSocket()
const store = useCounterStore()
// watch(userWebsocket.webSocketList, (newVal) => {
//       console.log('监听数据变化')
//       console.log(newVal)
//     }
// );

// const sendMsg = () => {
//     userWebsocket.sendMsg({data: 'hello'})
// }
// 获取用户信息
// const getTeachInfo = () => {
//   teachInfo({}, 'post').then((res: any) => {
//         if (res.code == 200) { 
//             localStorage.userinfo = JSON.stringify(res.data)
//         } else {
           
//         }
//     }).catch((err: any) => {
//         console.log(err)
//     })
// }
// 状态显示文本
const statusText = computed(() => {
  const statusMap: Record<string, string> = {
    INIT: '未初始化',
    CONNECTING: '连接中...',
    CONNECTED: '已连接',
    DISCONNECTED: '已断开'
  };
  return statusMap[status.value] || '未知状态';
});

// 状态显示样式
const statusClass = computed(() => {
  const classMap: Record<string, string> = {
    INIT: 'text-gray-500',
    CONNECTING: 'text-blue-500',
    CONNECTED: 'text-green-500',
    DISCONNECTED: 'text-red-500'
  };
  return classMap[status.value] || 'text-gray-500';
});
// 监听消息
watch(receivedMessages.value, (newVal:any, oldValue) => {
  console.log('监听数据变化',  newVal, oldValue)
})
onMounted(() => {
  console.log(store.setConnected, status.value,'websocket连接')
  if(status.value != 'CONNECTED' && status.value != 'CONNECTING') {
    nextTick(() => {
        const token = localStorage.getItem('token')
        init({
          url: `${wsUrl}?token=${token}&types=T`, // 替换为实际的WebSocket服务地址
          reconnectDelay: 2000,
          maxReconnectCount: 10,
          pingInterval: 30000,
          pingMessage: { type: 'ping', payload: '' }
        })
        connect();
    })
  }
  // getTeachInfo()
})
</script>

<template>
    <div>
        <!-- <a-button @click="sendMsg">Default Button</a-button> -->
        <!-- <start-live></start-live> -->
        连接状态: 
        <span :class="statusClass">{{ statusText }}</span>
        <!-- {{ receivedMessages }} -->
         <live-list></live-list>
    </div>
</template>

<style scoped>
.text-gray-500 { color: #666; }
.text-blue-500 { color: #2196f3; }
.text-green-500 { color: #4caf50; }
.text-red-500 { color: #f44336; }
</style>
